﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SocketWinFormHelloWorld
{
    public partial class Client : Form
    {
        private int _number;
        private int sum;
        private bool isStop=false;
        public Client()
        {
            InitializeComponent();
        }

        public Client(int number)
        {
            InitializeComponent();
            _number = number;
            this.Text = "Clinet-No."+_number.ToString();
    
            thread= new Thread(()=> ThreadSend()); 
            thread.IsBackground = true;
        }

        Thread thread;

        public void Send()
        {
            try
            {
                sum++;
                byte[] data = new byte[1024];
                IPEndPoint iep = new IPEndPoint(IPAddress.Parse(txtIP.Text), Convert.ToInt32(txtPort.Text));
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                data = Encoding.UTF8.GetBytes(this.Text + "-" + sum.ToString() + "-" + txtInfo.Text);
                socket.SendTo(data, data.Length, SocketFlags.None, iep);
            }
            catch
            {

            }
        }

        public void ThreadSend()
        {
            while (!isStop)
            {
                Thread.Sleep(5000);
                Send();
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            Send();
        }

        private void chkAuto_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAuto.Checked)
            {
                if (!thread.IsAlive)
                {
                    thread.Start();
                }
                isStop = false;
            }
            else
            {
                isStop = true;
            }
        }
    }
}
